#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
舆情监控系统 Web 仪表板
提供Web界面查看监控结果
"""

from flask import Flask, render_template, jsonify, request
import sqlite3
from datetime import datetime, timedelta
import json
import os

app = Flask(__name__)

class DashboardData:
    def __init__(self):
        self.db_path = 'sentiment_data.db'
        
    def get_connection(self):
        return sqlite3.connect(self.db_path)
        
    def get_recent_articles(self, limit=20):
        """获取最近的文章"""
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            SELECT id, title, url, source, keywords_found, created_at 
            FROM news_articles 
            ORDER BY created_at DESC 
            LIMIT ?
        ''', (limit,))
        articles = cursor.fetchall()
        conn.close()
        return articles
        
    def get_statistics(self):
        """获取统计数据"""
        conn = self.get_connection()
        cursor = conn.cursor()
        
        # 总文章数
        cursor.execute('SELECT COUNT(*) FROM news_articles')
        total_articles = cursor.fetchone()[0]
        
        # 今日文章数
        today = datetime.now().strftime('%Y-%m-%d')
        cursor.execute('SELECT COUNT(*) FROM news_articles WHERE DATE(created_at) = ?', (today,))
        today_articles = cursor.fetchone()[0]
        
        # 按来源统计
        cursor.execute('SELECT source, COUNT(*) FROM news_articles GROUP BY source')
        source_stats = cursor.fetchall()
        
        # 最近7天趋势
        cursor.execute('''
            SELECT DATE(created_at) as date, COUNT(*) as count 
            FROM news_articles 
            WHERE created_at >= datetime('now', '-7 days')
            GROUP BY DATE(created_at)
            ORDER BY date
        ''')
        trend_data = cursor.fetchall()
        
        conn.close()
        
        return {
            'total_articles': total_articles,
            'today_articles': today_articles,
            'source_stats': source_stats,
            'trend_data': trend_data
        }

dashboard = DashboardData()

@app.route('/')
def index():
    """主页"""
    return render_template('dashboard.html')

@app.route('/api/articles')
def api_articles():
    """获取文章API"""
    limit = request.args.get('limit', 20, type=int)
    articles = dashboard.get_recent_articles(limit)
    
    result = []
    for article in articles:
        result.append({
            'id': article[0],
            'title': article[1],
            'url': article[2],
            'source': article[3],
            'keywords': article[4],
            'created_at': article[5]
        })
    
    return jsonify(result)

@app.route('/api/statistics')
def api_statistics():
    """获取统计数据API"""
    stats = dashboard.get_statistics()
    return jsonify(stats)

@app.route('/api/sources')
def api_sources():
    """获取监控源详细信息API"""
    stats = dashboard.get_statistics()
    source_stats = stats['source_stats']
    
    result = []
    for source, count in source_stats:
        result.append({
            'source': source,
            'count': count
        })
    
    # 按文章数量降序排列
    result.sort(key=lambda x: x['count'], reverse=True)
    
    return jsonify(result)

if __name__ == '__main__':
    # 创建templates目录
    if not os.path.exists('templates'):
        os.makedirs('templates')
    
    print("舆情监控Web仪表板启动中...")
    print("访问地址: http://localhost:5000")
    app.run(debug=True, host='0.0.0.0', port=5000)